/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    void maxPathSum(TreeNode *root, int &s, int &d) {
        if (root==NULL) {
            s=d=0;
            return;
        }
        s=d=root->val;
        int ls,ld,rs,rd;
        ls=ld=rs=rd=0;
        if (root->left!=NULL) {
            maxPathSum(root->left, ls, ld);
            s=max(s, ls+root->val);
            d=max(d, ld);
        }
        if (root->right!=NULL) {
            maxPathSum(root->right, rs, rd);
            s=max(s, rs+root->val);
            d=max(d, rd);
        }
        d=max(d, s);
        d=max(d, ls+rs+root->val);
    }
public:
    int maxPathSum(TreeNode *root) {
        int s,d;
        maxPathSum(root, s, d);
        return d;
    }
};
